package servlet;

import bean.User;
import dao.UserDao;
import dao.impl.UserDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class AddServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username=req.getParameter("userId");
        String password=req.getParameter("password");
        String note=req.getParameter("note");
        User user=new User();
        HttpSession session = req.getSession();
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        PrintWriter out=resp.getWriter();
        UserDao userDao =new UserDaoImpl();
        System.out.println(username);
        if (userDao.login(username).getPassword()!=null){
            session.setAttribute("user", user);
            out.print("<script>alert('用户名已存在');history.go(-1);</script>");
            System.out.println("false");
        }else {
            user.setAdminName(username);
            user.setPassword(password);
            user.setNote(note);
            userDao.add(user);
            out.print("<script>alert('注册成功');history.go(-1);</script>");
            System.out.println("true");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
